/*
 * ShoppingCartPresenter.java
 * business
 *
 * Created by ChenTao on 2016/9/9.
 *
 * Copyright (c) 2016年 yidiandao. All rights reserved.
 */

package com.yidiandao.business.ui.main.shoppingcart;

import com.yidiandao.business.R;
import com.yidiandao.business.data.bean.Goods;
import com.yidiandao.business.data.model.IShoppingCartModel;
import com.yidiandao.business.data.model.IUserModel;
import com.yidiandao.business.data.response.RecommendGoodsListResponse;
import com.yidiandao.business.manager.GiftManager;
import com.yidiandao.business.manager.ShoppingCartManager;
import com.yidiandao.business.ui.widget.listview.DisplayListItem;
import com.yidiandao.business.ui.widget.view.SuperLoadingLayout;
import com.yidiandao.business.utils.UIUtils;

import java.util.List;

public class ShoppingCartPresenter implements ShoppingCartContract.Presenter {

    private ShoppingCartContract.View mShoppingCartView;

    private IShoppingCartModel mShoppingCartModel;

    private IUserModel mUserModel;

    private boolean showPayMenu;

    /**
     * 上一次页面加载的结果
     */
    private int mLastLoadResult;

    private List<DisplayListItem> mShoppingCartListItems;

    private HandleShoppingCartList mHandleShoppingCartList = new HandleShoppingCartList();

    public ShoppingCartPresenter(
            ShoppingCartContract.View view,
            IShoppingCartModel shoppingCartModel,
            IUserModel userModel) {
        mShoppingCartView = view;
        mShoppingCartModel = shoppingCartModel;
        mUserModel = userModel;

        mShoppingCartView.setPresenter(this);
    }

    @Override
    public void start() {
        // 判断是否需要刷新购物车
        // 从选择赠品页面返回是不需要刷新购物车的
        boolean refreshShoppingCart = mShoppingCartModel.needRefreshShoppingCart();
        if (refreshShoppingCart) {
            loadServerShoppingCartList();
        } else {
            // 需要重置SuperLayout为成功状态，否则会一直loading
            // 同时，需要设置DisplayListItem为上一次的数据
            mShoppingCartView.refreshContent(SuperLoadingLayout.STATE_SUCCESS);
            mShoppingCartView.setDisplayListItems(mShoppingCartListItems);
        }

        // 状态检查完成之后重置状态为 需要刷新购物车
        mShoppingCartModel.setNeedRefreshShoppingCart(true);
    }

    @Override
    public void loadServerShoppingCartList() {
        mShoppingCartModel.loadServerShoppingCartList(
                mShoppingCartView.getPagerTag(), mHandleShoppingCartList);
    }

    @Override
    public void showOrHidePayMenu() {

        mShoppingCartView.showOrHidePayMenuAndClearSelected(showPayMenu);
        changeShoppingCartMode(!showPayMenu);
        showPayMenu = !showPayMenu;
    }

    @Override
    public void initPayMenu() {
        mShoppingCartView.showOrHidePayMenuAndClearSelected(true);
        changeShoppingCartMode(false);
        showPayMenu = false;
    }

    @Override
    public void changeShoppingCartMode(boolean isEditMode) {
        ShoppingCartManager.getInstance().changeShoppingCartMode(isEditMode);
        mShoppingCartView.notifyAdapterDataSetChanged();
    }

    @Override
    public void delete() {
        mShoppingCartView.showLoadingDialog();

        String allSelectedGoodsCategoryId =
                ShoppingCartManager.getInstance().getAllSelectedGoodsRecIds();
        mShoppingCartModel.deleteGoodsFromServer(
                allSelectedGoodsCategoryId,
                mShoppingCartView.getPagerTag(),
                new IShoppingCartModel.OnShoppingCartOperatorListener() {
                    @Override
                    public void onSuccess() {
                        mShoppingCartView.dismissLoadingDialog();

                        mShoppingCartView.showToast(
                                UIUtils.getString(R.string.shopping_cart_delete_success));

                        // 不刷新购物车商品列表,否则会切换到非编辑模式下面
                        start();
                    }

                    @Override
                    public void onFailed() {
                        mShoppingCartView.dismissLoadingDialog();

                        mShoppingCartView.showToast(
                                UIUtils.getString(R.string.shopping_cart_delete_failed));
                    }
                });
    }

    @Override
    public void loadRecommendGoodsList() {
        mShoppingCartModel.loadShoppingCartRecommendGoods(
                mShoppingCartView.getPagerTag(),
                new IShoppingCartModel.OnLoadRecommendGoodsListener() {
                    @Override
                    public void onSuccess(RecommendGoodsListResponse.Data data) {
                        if (null != data) {
                            if (null != data.getGoodsList() && data.getGoodsList().size() != 0) {
                                mShoppingCartView.setRecommendGoodsList(data.getGoodsList());
                            }
                            if (null != data.getAdvert()) {
                                mShoppingCartView.setRecommendGoodsAdvert(data.getAdvert());
                            }
                            if (null != data.getNoticeList() && data.getNoticeList().size() != 0) {
                                mShoppingCartView.setNoticeInfo(data.getNoticeList());
                            }
                        }
                    }

                    @Override
                    public void onFailed() {
                    }
                });
    }

    @Override
    public void checkHasSelectedGoodsToDelete() {
        if (!ShoppingCartManager.getInstance().isShoppingCartHasSelectedGoods()) {
            mShoppingCartView.showToast(UIUtils.getString(R.string.shopping_cart_choose_delete_goods));
        } else {
            mShoppingCartView.showDeleteGoodsHintDialog();
        }
    }

    @Override
    public void checkStockAndBalance() {
        // 没有选择商品
        if (!ShoppingCartManager.getInstance().isShoppingCartHasSelectedGoods()) {
            mShoppingCartView.showToast(UIUtils.getString(R.string.shopping_cart_no_goods));
            return;
        }

        mShoppingCartView.showLoadingDialog();

        // 需要判断服务器库存的问题
        // 需要加入价格检验
        String allSelectedGoodsRecJson = ShoppingCartManager.getInstance().getAllSelectedGoodsRecJson();
        mShoppingCartModel.checkServerStockAndPrice(
                mShoppingCartView.getPagerTag(),
                allSelectedGoodsRecJson,
                new IShoppingCartModel.OnShoppingCartCheckStockAndPriceListener() {
                    @Override
                    public void onSuccess() {

                        mShoppingCartView.dismissLoadingDialog();

                        // 结算商品
                        mShoppingCartView.setPayButtonEnable(false);
                        mShoppingCartView.toConfirmOrderActivity();
                    }

                    @Override
                    public void onFailed() {
                        mShoppingCartView.dismissLoadingDialog();
                    }

                    @Override
                    public void onStockNotEnoughOrPriceChanged(String message) {
                        mShoppingCartView.dismissLoadingDialog();

                        // 库存不足 弹出库存不足的提示信息
                        mShoppingCartView.showStockNotEnoughOrPriceChangedDialog(message);
                    }
                });
    }

    @Override
    public boolean checkLogin() {

        if (mUserModel.isLogin()) {
            return true;
        }

        // 在购物车页面被 挤出去，则显示错误的页面
        mLastLoadResult = SuperLoadingLayout.STATE_ERROR;
        mShoppingCartView.refreshContent(mLastLoadResult);

        return false;
    }

    @Override
    public void notifyShoppingCartStatisticsChanged() {
        ShoppingCartManager.getInstance().notifyShoppingCartStatisticsChanged();
    }

    @Override
    public void loadCartListByWhenGoodsCountChanged(final Goods goods) {
        mShoppingCartView.showLoadingDialog();

        mShoppingCartModel.changeNumberByOne(
                goods,
                mShoppingCartView.getPagerTag(),
                new IShoppingCartModel.OnUpdateShoppingCartCountListener() {
                    @Override
                    public void onSuccess() {
                        // 刷新布局
                        mShoppingCartView.notifyAdapterDataSetChanged();

                        // 同时，需要底部统计的数量
                        notifyShoppingCartStatisticsChanged();

                        // 重新计算是否全选
                        ShoppingCartManager.getInstance().notifyTotalSelectedStateChanged();
                    }

                    @Override
                    public void onFailed() {
                        // 刷新布局
                        mShoppingCartView.notifyAdapterDataSetChanged();
                    }

                    @Override
                    public void onFinal() {
                        mShoppingCartView.dismissLoadingDialog();
                    }
                });
    }

    @Override
    public void postShoppingCartData() {
        // 当前购物车的数据
        String recJson = ShoppingCartManager.getInstance().getAllSelectedGoodsRecJson();
        String favourableJson = GiftManager.getInstance().getBalanceGiftListJson();

        // 告知服务器
        mShoppingCartModel.postShoppingCartData(mShoppingCartView.getPagerTag(), recJson, favourableJson,
                new IShoppingCartModel.OnShoppingCartOperatorListener() {
                    @Override
                    public void onSuccess() {
                        mShoppingCartView.toConfirmOrderActivity();
                    }

                    @Override
                    public void onFailed() {

                    }
                });
    }

    /**
     * 处理已显示购物车商品列表
     */
    private class HandleShoppingCartList implements IShoppingCartModel.OnLoadShoppingCartListListener {
        @Override
        public void onSuccess(List<DisplayListItem> displayListItems) {

            mShoppingCartView.dismissLoadingDialog();

            // 页面加载的结果
            mLastLoadResult = mShoppingCartView.checkResultObject(displayListItems);
            mShoppingCartView.refreshContent(mLastLoadResult);

            // 保存购物车列表
            mShoppingCartListItems = displayListItems;

            mShoppingCartView.setDisplayListItems(displayListItems);

            mShoppingCartView.setRefreshComplete();

            mShoppingCartView.showOrHidePayMenu(true);
            changeShoppingCartMode(false);
            showPayMenu = false;

            if (mLastLoadResult == SuperLoadingLayout.STATE_EMPTY) {
                // 购物车为空时，需要加载推荐商品列表
                loadRecommendGoodsList();
            }
        }

        @Override
        public void onFailed() {
            mLastLoadResult = SuperLoadingLayout.STATE_ERROR;
            mShoppingCartView.refreshContent(mLastLoadResult);
            mShoppingCartView.dismissLoadingDialog();

            mShoppingCartView.setRefreshComplete();
        }
    }
}
